package com.example.sbeducation.controller;

import com.example.sbeducation.common.Result;
import com.example.sbeducation.dto.LoginDTO;
import com.example.sbeducation.dto.UserInfoDTO;
import com.example.sbeducation.dto.PasswordChangeDTO;
import com.example.sbeducation.entity.User;
import com.example.sbeducation.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserController {

  @Autowired
  private UserService userService;

  /**
   * 学生登录
   */
  @PostMapping("/student/login")
  public Result<UserInfoDTO> studentLogin(@Valid @RequestBody LoginDTO loginDTO) {
    UserInfoDTO userInfoDTO = userService.studentLogin(loginDTO);
    return Result.success(userInfoDTO);
  }

  /**
   * 教师登录
   */
  @PostMapping("/teacher/login")
  public Result<UserInfoDTO> teacherLogin(@Valid @RequestBody LoginDTO loginDTO) {
    UserInfoDTO userInfoDTO = userService.teacherLogin(loginDTO);
    return Result.success(userInfoDTO);
  }

  /**
   * 获取用户联系人列表
   * 学生获取所有教师，教师获取所有学生
   */
  @GetMapping("/contacts")
  public Result<List<UserInfoDTO>> getContacts(@RequestParam Long userId) {
    List<UserInfoDTO> contacts = userService.getContactsByUserRole(userId);
    return Result.success(contacts);
  }

  /**
   * 获取用户信息
   */
  @GetMapping("/{userId}")
  public Result<UserInfoDTO> getUserInfo(@PathVariable Long userId) {
    User user = userService.getUserById(userId);
    UserInfoDTO userInfoDTO = new UserInfoDTO();
    // 这里需要转换实体到DTO
    userInfoDTO.setId(user.getId());
    userInfoDTO.setUsername(user.getUsername());
    userInfoDTO.setRole(user.getRole());
    userInfoDTO.setRealName(user.getRealName());
    userInfoDTO.setEmail(user.getEmail());
    userInfoDTO.setPhone(user.getPhone());
    userInfoDTO.setAvatar(user.getAvatar());
    return Result.success(userInfoDTO);
  }

  /**
   * 更新用户信息
   */
  @PutMapping("/update")
  public Result<Void> updateUserInfo(@RequestBody UserInfoDTO userInfoDTO) {
    log.info("收到更新用户信息请求: {}", userInfoDTO);
    try {
      userService.updateUserInfo(userInfoDTO);
      log.info("用户信息更新成功: {}", userInfoDTO.getId());
      return Result.success("更新成功");
    } catch (Exception e) {
      log.error("用户信息更新失败", e);
      return Result.error(500, "更新失败: " + e.getMessage());
    }
  }

  /**
   * 修改密码
   */
  @PutMapping("/password")
  public Result<Void> changePassword(@Valid @RequestBody PasswordChangeDTO passwordChangeDTO) {
    userService.changePassword(passwordChangeDTO);
    return Result.success("密码修改成功");
  }
}